package org.moonshot.cvm;

public abstract class CVMClass implements I_ChattyClass
{
	/**
	 * Check that an instance is of an expected type, and throw an exception if it is not.
	 * @param <T>
	 * @param expectedClass
	 * @param aInstance
	 * @return The instance, correctly cast, if and only if it is non-null, non-nil, and of a type compatible with the expected type.
	 * @throws CVMRuntimeException
	 */
	@SuppressWarnings ("unchecked")
    protected final<T> T checkClassHandling(ChattyVM aVM, Class<? extends T> expectedClass, Object aInstance)
		throws CVMRuntimeException
	{
		if( aInstance == null )
			throw new CVMRuntimeException ("Invalid argument; expected non-null");
		
		if( aInstance == aVM.NIL )
			throw new CVMRuntimeException ("Invalid argument; expected non-nil");
		
		if( ! expectedClass.isAssignableFrom (aInstance.getClass ()) )
			throw new CVMRuntimeException ("Instance not of expected type; got "+aInstance.getClass ()+", expected "+expectedClass);
		
		return (T) aInstance;
	}
}
